package cn.edu.zjicm.wordsnet_d.synchronize;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import cn.edu.zjicm.wordsnet_d.download.JudgeNetwork;
import android.content.Context;
import android.os.Handler;

public class ForgetPwdInterface extends ServerInterface{

	// 通知UI刷新的handler和msg常量
	public static final int MSG_START = 0; // 开始
	public static final int MSG_SUCCESS = 1; // 成功
	public static final int MSG_BAD_NETWORK = 2; // 网络链接错误
	public static final int MSG_CONFIRM_EMAIL = 3; // 没有该邮箱
	public static final int MSG_WEB_SITE_ACCESS_FAILURE = 6; // 无法访问web site
	public static final int MSG_UNSUCCESS = 7; // 邮件发送失败
	public static final int MSG_REPEAT_TIMER = 8; // 重新发送TimerTask
	public static final int MSG_SUCCESS_TO_CHANGE = 9; // 验证成功
	public static final int MSG_EMAIL_ERROR = 10; // 邮箱格式错误
	public static final int MSG_ERROR_CODE = 11; // 验证码错误

	public static final String ERROR_MSG1 = "no such user!";
	public static final String ERROR_MSG2 = "send mail error";

	private static ForgetPwdInterface mInstance;
	private Map<String, Object> map;
	
	public static ForgetPwdInterface getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new ForgetPwdInterface(context);
		}
		return mInstance;
	}

	private ForgetPwdInterface(Context context) {
		super(context);
	}

	// 发送邮件
	public void toSendEmail(String email, Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {// 如果是wifi状态，直接下载
			map = new HashMap<String, Object>();
			map.put("loginId", email);
			new SynThread(map, handler, SEND_FORGET_MAIL).start();
		} else {
			handler.sendMessage(handler.obtainMessage(ForgetPwdInterface.MSG_BAD_NETWORK));
		}
	}

	// 验证码
	public void toConfirmCode(String loginId, String code, Handler handler) {
		// TODO Auto-generated method stub
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {// 如果是wifi状态，直接下载
			map = new HashMap<String, Object>();
			map.put("loginId", loginId);
			map.put("code", code);
			new SynThread(map, handler, VALIDATE_CODE).start();
		} else {
			handler.sendMessage(handler.obtainMessage(ForgetPwdInterface.MSG_BAD_NETWORK));
		}
	}

	// 设置新密码
	public void toChangePwdWithCode(String loginId, String code, String newPwd, Handler handler) {
		if (JudgeNetwork.getInstance(context).isWifiConnected() || JudgeNetwork.getInstance(context).isMobileConnected()) {// 如果是wifi状态，直接下载
			map = new HashMap<String, Object>();
			map.put("loginId", DefaultTripleDES.getInstance().encrypt(loginId));
			map.put("code", DefaultTripleDES.getInstance().encrypt(code));
			map.put("newPwd", DefaultTripleDES.getInstance().encrypt(newPwd));
			new SynThread(map, handler, CHANGE_PWD).start();
		} else {
			handler.sendMessage(handler.obtainMessage(ForgetPwdInterface.MSG_BAD_NETWORK));
		}
	}

	public class SynThread extends Thread {
		Map<String, Object> map;
		Handler handler;
		String postUrl;
		int what;

		public SynThread(Map<String, Object> map, Handler handler, String postUrl) {
			this.map = map;
			this.handler = handler;
			this.postUrl = postUrl;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			DefaultHttpClient client = new DefaultHttpClient();
			setClientTimeout(client);
			List<NameValuePair> pairList = new ArrayList<NameValuePair>();
			NameValuePair nameValuePair;
			Iterator it = map.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Entry) it.next();
				nameValuePair = new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue());
				pairList.add(nameValuePair);
			}
			try {
				HttpEntity entity = new UrlEncodedFormEntity(pairList);
				HttpPost post = new HttpPost(postUrl);
				post.setEntity(entity);
				HttpResponse response = client.execute(post);
				if (response.getStatusLine().getStatusCode() == 200) {
					String str = EntityUtils.toString(response.getEntity(), "utf-8");
					System.out.println("服务器传来：" + str);
					if (postUrl.equals(ForgetPwdInterface.CHANGE_PWD)) {
						str = DefaultTripleDES.getInstance().decrypt(str);
					}

					JSONObject result = new JSONObject(str);
					boolean success = result.getBoolean("success");

					if (success) {
						if (postUrl.equals(ForgetPwdInterface.VALIDATE_CODE)) {
							boolean valid = result.getBoolean("valid");
							if (valid)
								what = ForgetPwdInterface.MSG_SUCCESS_TO_CHANGE;
							else
								what = ForgetPwdInterface.MSG_ERROR_CODE;
						}

						else
							what = ForgetPwdInterface.MSG_SUCCESS;
					} else {
						if (postUrl.equals(ForgetPwdInterface.SEND_FORGET_MAIL)) {
							String message = result.getString("message");
							if (message.startsWith("no"))
								what = ForgetPwdInterface.MSG_CONFIRM_EMAIL;
							else if (message.startsWith("send"))
								what = ForgetPwdInterface.MSG_UNSUCCESS;

						} else {
							what = ForgetPwdInterface.MSG_UNSUCCESS;
						}
					}
				} else {
					what = ForgetPwdInterface.MSG_WEB_SITE_ACCESS_FAILURE;
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				what = ForgetPwdInterface.MSG_WEB_SITE_ACCESS_FAILURE;
			}
			handler.sendMessage(handler.obtainMessage(what));
		}
	}

}
